package com.example.bbs.ui.activity;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.bbs.R;
import com.example.bbs.base.Data;
import com.example.bbs.bean.Notice;
import com.example.bbs.bean.Post;
import com.example.bbs.bean.Comment;
import com.example.bbs.config.HttpConstant;
import com.example.bbs.ui.view.RichTextView;
import com.example.bbs.ui.tool.RecyclerAdapterLoadMoreWrapper;
import com.example.bbs.util.BaseUtil;
import com.example.bbs.util.HttpUtil;
import com.nostra13.universalimageloader.utils.L;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;

import okhttp3.FormBody;

public class DisplayActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String INTENT_EXTRA_POST = "post"; // type: Post
    static final String LOG_TAG = DisplayActivity.class.getSimpleName();

    public class ItemViewHolder extends RecyclerView.ViewHolder {

        Comment comment;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
        }

        public void setComment(Comment comment) {
            this.comment = comment;
            TextView contentTextView = itemView.findViewById(R.id.tv_comment_content);
            contentTextView.setText(comment.getContent());
            Log.d(LOG_TAG, "1");
        }
    }

    public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        @NonNull
        @Override
        public DisplayActivity.ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(parent.getContext(), R.layout.view_item_comment_box, null);
            Log.d(LOG_TAG, "4");
            return new DisplayActivity.ItemViewHolder(view);
        }
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ((DisplayActivity.ItemViewHolder)holder).setComment(mCommentList.get(position));
        }
        @Override
        public int getItemCount() {
            return mCommentList.size();
        }
    }

    String c_text;
    TextView tvTitle;
    TextView comment;
    Button follow;
    TextView tvUserId;
    TextView tvPosition;
    RichTextView rtvContent;
    ImageView ivLike;
    ImageView ivShare;
    ImageView ivAvatar;
    RecyclerView rvCommentList;
    SwipeRefreshLayout srlCommentList;
    MyAdapter mAdapter = new MyAdapter();
    List<Comment> mCommentList = new ArrayList<>();
    InputMethodManager imm;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(LOG_TAG, "onCreate");
        setContentView(R.layout.activity_display);
        initView();
        initOnClickListener();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d(LOG_TAG, "onOptionsItemSelected, MenuItem: " + item.getItemId());
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            // rtnValue = true, 阻拦默认 ActionBar 的返回（这会重新创建一个 Activity）。
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(LOG_TAG, "onResume");

        try {
            CompletableFuture.runAsync(this::load).get(); // 初始化
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(LOG_TAG, "onPause");

        rtvContent.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(LOG_TAG, "onDestroy");

        rtvContent.onDestroy();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void initView() {
        tvTitle = findViewById(R.id.tv_title);
        rtvContent = findViewById(R.id.rtv_content);
        ivLike = findViewById(R.id.iv_like);
        ivShare = findViewById(R.id.iv_share);
        ivAvatar = findViewById(R.id.iv_Avatar_display);
        comment = findViewById(R.id.btn_comment);
        follow = findViewById((R.id.btn_follow));
        tvUserId = findViewById(R.id.tv_userid);
        tvPosition = findViewById(R.id.tv_position_display);

        rvCommentList = findViewById(R.id.rv_comment_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvCommentList.setAdapter(mAdapter);
        rvCommentList.setLayoutManager(layoutManager);
        Log.d(LOG_TAG, "2");

        Intent intent = getIntent();
        Post post = intent.getParcelableExtra(INTENT_EXTRA_POST);
        tvTitle.setText(post.getTitle());
        if (post.getContent() == null || post.getContent().isEmpty()) {
            Log.d(LOG_TAG, "try to get essay");
            FormBody formBody = new FormBody.Builder()
                    .add(HttpConstant.FIELD_PARAM_1, "" + post.getId())
                    .build();
            HttpUtil.postAsync(HttpConstant.REQUEST_GET_ESSAY, formBody, (response) -> runOnUiThread(() -> {
                if (response == null || !response.getBoolean(HttpConstant.FIELD_REPLY)) {
                    Log.d(LOG_TAG, "get essay failed");
                    rtvContent.init(getString(R.string.default_content), false);
                } else {
                    post.setContent(response.getJSONObject(HttpConstant.FIELD_DATA).getString("content"));
                    Log.d(LOG_TAG, "get essay success: " + post.getContent());
                    rtvContent.init(post.getContent(), false);
                }
            }));
        } else {
            rtvContent.init(post.getContent(), false);
        }

    }

    public void initOnClickListener() {
        ivLike.setOnClickListener(this);//点赞
        ivShare.setOnClickListener(this);//分享
        ivAvatar.setOnClickListener(this);//头像点击
        comment.setOnClickListener(this);//评论
        follow.setOnClickListener(this);//关注
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        if (id == R.id.iv_share) {
            Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("image/*");
            // TODO(Mid): 分享截长图和在APP中打开
//            sendIntent.putExtra(Intent.EXTRA_TEXT, rtvContent.generateAbstract());
//            sendIntent.putExtra(Intent.EXTRA_SUBJECT, "test title");
//            startActivity(Intent.createChooser(sendIntent, "share title"));
            ScrollView scrollView = findViewById(R.id.display_scrollview);
            File file = new File(savePic(compressImage(getBitmapByView(scrollView))));
            sendIntent.putExtra(Intent.EXTRA_SUBJECT, Uri.fromFile(file)); //需要分享的文件URI
            startActivity(Intent.createChooser(sendIntent, "title"));
            //截长图
//            share();
        } else if (id == R.id.iv_like) {
            like();
        } else if (id == R.id.iv_Avatar_display){
            Intent intent = new Intent();
            intent.setClass(DisplayActivity.this ,PersonalInfo.class);
            Intent intent_get = getIntent();
            Post post = intent_get.getParcelableExtra(INTENT_EXTRA_POST);
            Bundle bundle=new Bundle();
            bundle.putInt("id",post.getAuthorId());
            intent.putExtra("bundle",bundle);
            DisplayActivity.this.startActivity(intent);

        }else if (id == R.id.btn_comment){
            uploadComment(true);
            this.finish();
        }
        else if (id == R.id.btn_follow){
            follow();
        }
    }

    private void load() {
        Intent intent = getIntent();
        Post post = intent.getParcelableExtra(INTENT_EXTRA_POST);

        FormBody formBody_user = new FormBody.Builder()
                .add(HttpConstant.FIELD_USERID, "" + post.getAuthorId())
                .build();
        HttpUtil.postAsync(HttpConstant.REQUEST_GET_USER, formBody_user, (response) -> {
            if (response != null  && response.getBoolean(HttpConstant.FIELD_REPLY)) {
                Log.d(LOG_TAG, "get username success");
                JSONObject result = response.getJSONObject(HttpConstant.FIELD_DATA);
                tvUserId.setText("" + result.getString("name"));
            }
            else
                Log.d(LOG_TAG, "get username failure");
        });

        FormBody formBody = new FormBody.Builder()
                .add(HttpConstant.FIELD_POST_ID,post.getId()+"")
                .build();
        JSONObject json = HttpUtil.post(HttpConstant.REQUEST_COMMENT_GET, formBody);
        if (json == null || !json.getBoolean(HttpConstant.FIELD_REPLY))
            return;
        JSONArray result = json.getJSONArray(HttpConstant.FIELD_DATA);
        mCommentList.clear();
        for (int i = 0; i < result.size(); i++) {
            Comment newComment= result.getObject(i, Comment.class);
            mCommentList.add(newComment);
            Log.d(LOG_TAG, "comment box updated: num: " + mCommentList.size());
        }
        mAdapter.notifyDataSetChanged();
        Log.d(LOG_TAG, "3");

        if(post.isLikeOr()){
            Drawable tipsArrow = ivLike.getDrawable();
            tipsArrow.setColorFilter(getColor(R.color.red), PorterDuff.Mode.SRC_ATOP);
            ivLike.setImageDrawable(tipsArrow);
            like_notice();
        }
        else {
            Drawable tipsArrow = ivLike.getDrawable();
            tipsArrow.setColorFilter(getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
            ivLike.setImageDrawable(tipsArrow);
        }
    }

    private void uploadComment(boolean published) {
        Log.d(LOG_TAG, "upload comment here");
        if (Data.myself == null) {
            BaseUtil.showToast(R.string.toast_please_login); // 检查是否登录
            return;
        }
        EditText etComment = (EditText)findViewById(R.id.et_comment);
            Log.d(LOG_TAG, "upload content: " + etComment.getText().toString());
                Intent intent = getIntent();
                Post post = intent.getParcelableExtra(INTENT_EXTRA_POST);
                Comment newComment = new Comment(-1,etComment.getText().toString(), Data.myself.getId(),post.getId());
                HttpUtil.postAsync(HttpConstant.REQUEST_COMMENT_POST, JSON.toJSONString(newComment), (response) -> {
                    if (response != null  && response.getBoolean(HttpConstant.FIELD_REPLY))
                        Log.i(LOG_TAG, "add comment success");
                    else
                        Log.w(LOG_TAG, "add comment failure");
                });

            }


    private void like(){
        if (Data.myself == null) {
            BaseUtil.showToast(R.string.toast_please_login);
            return;
        }
        Intent intent = getIntent();
        Post post = intent.getParcelableExtra(INTENT_EXTRA_POST);
        FormBody formBody = new FormBody.Builder()
                .add(HttpConstant.FIELD_POST_ID, "" + post.getId())
                .build();

        Log.d(LOG_TAG, "" +post.getId());
        HttpUtil.postAsync(HttpConstant.REQUEST_LIKE, formBody, (response) -> runOnUiThread(() -> {
            if (response == null || !response.getBoolean(HttpConstant.FIELD_REPLY)) {
                Log.d(LOG_TAG, "like failed");
                BaseUtil.showToast("like failed");
            } else {
                Log.d(LOG_TAG, "like success");
                Log.d(LOG_TAG,"" + response.getBoolean(HttpConstant.FIELD_DATA));
                if(response.getBoolean(HttpConstant.FIELD_DATA)){
                    BaseUtil.showToast("like succeeded");
                    Drawable tipsArrow = ivLike.getDrawable();
                    tipsArrow.setColorFilter(getColor(R.color.red), PorterDuff.Mode.SRC_ATOP);
                    ivLike.setImageDrawable(tipsArrow);
                    like_notice();
                }
                else {
                    BaseUtil.showToast("like canceled");
                    Drawable tipsArrow = ivLike.getDrawable();
                    tipsArrow.setColorFilter(getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
                    ivLike.setImageDrawable(tipsArrow);
                }
            }
        }));
    }

    private void follow(){//关注
        if (Data.myself == null) {
            BaseUtil.showToast(R.string.toast_please_login);
            return;
        }
        Intent intent = getIntent();
        Post post = intent.getParcelableExtra(INTENT_EXTRA_POST);
        FormBody formBody = new FormBody.Builder()
                .add(HttpConstant.FIELD_USERID, "" + post.getAuthorId())
                .build();

        Log.d(LOG_TAG, "" +post.getAuthorId());
        HttpUtil.postAsync(HttpConstant.REQUEST_FOLLOW, formBody, (response) -> runOnUiThread(() -> {
            if (response == null || !response.getBoolean(HttpConstant.FIELD_REPLY)) {
                Log.d(LOG_TAG, "follow failed");
                BaseUtil.showToast("follow failed");
            } else {
                Log.d(LOG_TAG, "follow success");
                BaseUtil.showToast("follow succeeded");
                follow.setText("followed");
                follow.setEnabled(false);
//                Log.d(LOG_TAG,"" + response.getBoolean(HttpConstant.FIELD_DATA));
//                if(response.getBoolean(HttpConstant.FIELD_DATA)){
//
//                }
//                else {
//                    BaseUtil.showToast("follow canceled");
//                }
            }
        }));
    }

    //点赞后发送通知
    private void like_notice(){
        Intent intent = getIntent();
        Post post = intent.getParcelableExtra(INTENT_EXTRA_POST);
        Date time = new Date(System.currentTimeMillis());
        int user_id = post.getAuthorId();
        boolean reador = false;
        String notice_content = "" + Data.myself.getName() + "点赞了你的帖子，快去看看吧";

        Notice like_notice = new Notice(time.toString(),notice_content,user_id,reador);
        HttpUtil.postAsync(HttpConstant.REQUEST_ADD_NOTICE, JSON.toJSONString(like_notice), (response) -> {
            if (response != null  && response.getBoolean(HttpConstant.FIELD_REPLY))
                Log.i(LOG_TAG, "add notice success");
            else
                Log.w(LOG_TAG, "add notice failure");
        });
    }

//    //分享
//    private void share(){
//        ScrollView scrollView = findViewById(R.id.display_scrollview);
//        savePic(compressImage(getBitmapByView(scrollView)));
//    }

    /**
     * 截取scrollview的屏幕
     * @param scrollView
     * @return
     */
    public static Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        // 获取scrollview实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
            scrollView.getChildAt(i).setBackgroundColor(
                    Color.parseColor("#ffffff"));
        }
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

    /**
     * 压缩图片
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
        while (baos.toByteArray().length / 1024 > 100) {
            // 重置baos
            baos.reset();
            // 这里压缩options%，把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            // 每次都减少10
            options -= 10;
        }
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        // 把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    /**
     * 保存到sdcard
     * @param b
     * @return
     */
    public static String savePic(Bitmap b) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
                Locale.US);
        File outfile = new File("/sdcard/");
        // 如果文件不存在，则创建一个新文件
        if (!outfile.isDirectory()) {
            try {
                outfile.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String fname = outfile + "/" + sdf.format(new Date()) + ".png";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fname);
            if (null != fos) {
                b.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d(LOG_TAG,"save pic");
        return fname;
    }
}